<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="layout :: common_header(~{::title})">
    <title>生成采购单 - [[${T(com.b2c.erp.DataConfigObject).getInstance().getSysName()}]]</title>
</head>
<body th:replace="layout :: common_body(~{::div.layui-body})">

<div class="layui-body" style="padding:15px;top: 0px;">

    <!-- start sp-wrapper -->
    <link rel="stylesheet" href="/sb/stock.css"/>
    <div class="sp-wrapper">
        <h2 class="sp-title"><span>生成采购单</span></h2>
        <form action="/purchase/add" method="post" id="sp-form">
            <input type="hidden" name="transType" th:value="${transType}">
            <input type="hidden" name="srcOrderId" th:value="${srcOrderId}">
            <div class="sp-tool">
			<span class="fl">
                <b>供应商：
                    <select name="supplierId" id="supplierId">
                        <option value="">请选择供应商</option>
                        <option th:each="item:${contacts}" th:value="${item.id}" th:text="${item.name}">1111111</option>
                    </select>
                </b>
                <b>单据日期：<input type="text" name="billDate" th:value="${time}" class="date ui-input ui-datepicker-input" autocomplete="off"
                               id="form_date"></b>
                <b>单据编号：[[${billNo}]]
                <input type="hidden" name="billNo" th:value="${billNo}"/>
                </b>
            </span>
                <span class="fr"><i class="save" id="save">保存单据</i>
                    <!--                    <i class="add" id="add">新增</i>-->
                </span>
            </div>
            <div class="sp-table">
                <table>
                    <thead>
                    <tr>
                        <th>SKU</th>
                        <th>商品图片</th>
                        <th>商品规格</th>
                        <th>单位</th>
                        <th>数量</th> 
                       
                        <th>购货单价</th>
                        <th>折扣率(%)</th>
                        <th>折扣额</th>
                        <th>快递费</th> 
                        <th>购货金额</th>
                        <th>备注</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="sp-data">
                    <tr th:each="item:${itemList}">
                        <td width="400px">
                            <input type="hidden" name="specNumber" class="specNumber" th:value="${item.specNumber}">
                            <input type="hidden" name="itemId" class="itemId" th:value="${item.itemId}">
                            <input type="hidden" name="specId" class="specId" th:value="${item.specId}">
                            <input type="hidden" name="goodsId" class="goodsId" th:value="${item.goodsId}">
                            <input type="hidden" name="goodsNumber" class="goodsNumber" th:value="${item.goodsNumber}">
                            <input type="text" class="goods" placeholder="请输入商品编码" th:value="${item.specNumber + '  ' + item.name}" autocomplete="off" style="width: 100%"/>
                        </td>
                        <td><img style="width: 50px;height: 50px" class="img" th:src="${item.colorImage}" /></td>
                        <td><input type="text" readonly class="spec" placeholder="规格" th:value="${item.colorValue + item.styleValue + item.sizeValue}" /></td>
                        <td><input type="text" readonly class="unit" placeholder="单位"/></td>
                        <td><input type="text" name="quantity" class="quantity" placeholder="请输入" th:value="${item.quantity}" /></td>
                        <td><input type="text" name="price" class="price" placeholder="请输入" th:value="${#numbers.formatDecimal(item.costPrice + item.freight,0,2)}" /></td>
                        <td><input type="text" name="disRate" class="disRate" placeholder="请输入" value="0" /></td>
                        <td><input type="text" name="disAmount" class="disAmount" readonly="readonly" placeholder="折扣金额" value="0.00" /></td>
                        <td><input type="text" name="freight" class="freight" placeholder="快递费" th:value="${#numbers.formatDecimal(item.freight,0,2)}" /></td>
                        <td><input type="text" name="amount" class="amount" readonly="readonly" placeholder="购货金额" th:value="${(item.costPrice  * item.quantity) + item.freight}" />
                        </td>
                        <td><input type="text" name="note" class="note" placeholder="请输入"/></td>
                        <td>
                            <i class="delete">-</i>
<!--                            <i class="add">+</i>-->

                        </td>
                    </tr>
                    
                    <!-- <tr>
                        <td>
                            <input type="hidden" name="specNumber" class="specNumber">
                            <input type="hidden" name="specId" class="specId">
                            <input type="hidden" name="goodsId" class="goodsId">
                            <input type="hidden" name="goodsNumber" class="goodsNumber">
                            <input type="text" class="goods" placeholder="请输入商品编码" autocomplete="off" style="width: 100%"/></td>
                        <td><img style="width: 50px;height: 50px" class="img" /></td>
                        <td><input type="text" readonly class="spec" placeholder="规格"/></td>
                        <td><input type="text" readonly class="unit" placeholder="单位"/></td>
                        <td><input type="text" name="quantity" class="quantity" placeholder="请输入"/></td>
                        <td><input type="text" name="price" class="price" placeholder="请输入"/></td>
                        <td><input type="text" name="disRate" class="disRate" placeholder="请输入"/></td>
                        <td><input type="text" name="disAmount" class="disAmount" readonly="readonly"
                                   placeholder="折扣金额"/></td>
                        <td><input type="text" name="amount" class="amount" readonly="readonly" placeholder="购货金额"/>
                        </td>
                        <td><input type="text" name="note" class="note" placeholder="请输入"/></td>
                        <td><i class="delete">-</i>
                            <i class="add">+</i>
                        </td>
                    </tr> -->

                    </tbody>
                </table>
            </div>
            <div class="sp-tool">
                <p>
                    <b><em>优惠率：</em><input name="invoiceDisRate" type="number" value="0" class="text" id="yhl">%</b>
                    <b><em>优惠金额：</em><input type="number" name="invoiceDisAmount" readonly="readonly" id="yhje"
                                            value="0.00" class="text"></b>
                    <b><em>优惠后金额：</em><input type="number" readonly="readonly" name="invoiceAmount" value="0.00"
                                             class="text" id="yhhje"></b>
                    <b><em>本次付款：</em><input type="number" name="rpAmount" value="0.00" class="text" id="bcfk"></b>
                    <b><em>总数量：</em><span style="color: red" id="totalCount">0</span></b>
                </p>
                <p>
                    <b><em>本次欠款：</em><input type="number" name="arrears" value="0.00" class="text" id="bcqk"></b>
                    <b><em>制单人：</em><input type="text" name="userName" id="userName" th:value="${T(com.b2c.erp.DataConfigObject).getInstance().getLoginUserName()}" class="text"></b>
                    <b><em>合同号：</em><input type="text" name="contractNo" th:value="${month}" placeholder="请输入合同号" class="text"></b>
                    <!--<b><em>采购合同：</em><input type="file"><input type="button" value="查看"></b></p>-->
                    <!--<p><b><em>制单人：</em><input type="text" th:value="${userName}" readonly class="text"></b></p>-->
            </div>
        </form>
    </div>

    <script type="text/javascript" src="/sb/jquery.min.js"></script>
    <script type="text/javascript" src="/sb/Tips.min.js"></script>
    <script th:inline="javascript">
        /*<![CDATA[*/

        var housesData = /*[[${housesJSON}]]*/ null;
        /*]]>*/
    </script>

    <script type="text/javascript">
        var skuPush = [];//添加的sku

        $(function () {
            // console.log(JSON.stringify(housesData));

            function render(data) {

                for (var i = 0, n = data.length, tpl = ''; i < n; i++) {
                    var price=data[i].price==0 ? '' : data[i].price;
                    var freight=data[i].freight==0 ? '' : data[i].freight;
                    var sizeValue = data[i].sizeValue ==null ? '' :data[i].sizeValue;
                    var styleValue = data[i].styleValue ==null ? '' :data[i].styleValue;
                    var goodsName = data[i].name + "_" + data[i].colorValue+ " " + styleValue + " " + sizeValue + ' SKU:' + data[i].specNumber
                    // var goodsName = data[i].specNumber;
                    tpl += '<li data-id="' + data[i].goodsId + '" data-unit="' + data[i].unit + '" goods-no="' + data[i].goodsNumber +
                            '" color-image="'+data[i].colorImage +'" goods-name="'+data[i].name +
                        '" spec-no="' + data[i].specNumber + '" spec-name="' + data[i].colorValue+ " " + styleValue + " " + sizeValue + '" spec-id="' + data[i].specId +
                        '" data-quantity="' + data[i].quantity + '" data-price="' + price + '" data-freight="'+freight
                        '" data-rate="' + data[i].disRate + '" data-rebate="' + data[i].disAmount +
                        '" data-amount="' + data[i].amount + '">' + goodsName + '</li>';
                }
                $('.sp-result').html(tpl);
            }

            function init() {
                var $box = $('<ul class="sp-result"></ul>').appendTo($('body'));
                var $status = false;
                var $id = null; //商品ID
                var $goodsName = null; //商品
                var $goodsId = null; //商品id
                var $goodsNumber = null; //商品编码
                var $specId = null; //商品规格id
                var $specNumber = null; //商品规格编号
                var $unit = null; //单位
                var $specName = null;//规格名
                var $colorImage = null;//规格图片
                // var $address = null; //仓库
                var $quantity = null; //数量
                var $price = null; //购买单价
                var $disRate = null; //折扣率
                var $disAmount = null; //折扣额
                var $amount = null; //购货金额
                // var $number = null; //序列号
                // var $note = null; //备注

                $(document).click(function (e) {
                    if ($status) {
                        $box.hide();
                        $status = false;
                    }
                });
                $('#sp-data').delegate('.goods', 'click', function (e) {
                    e.stopPropagation();
                    var _this = $(this);
                    var _tr = _this.parent('td').parent('tr');
                    // $id = _tr.find('.goodsId'); //商品ID
                    $goodsName = _this;
                    $unit = _tr.find('.unit'); //单位
                    $specNumber = _tr.find('.specNumber'); //商品规格编码
                    $goodsNumber = _tr.find('.goodsNumber'); //商品规格编码
                    $goodsId = _tr.find('.goodsId'); //商品id
                    $specId = _tr.find('.specId'); //商品id
                    $specName = _tr.find('.spec');
                    $colorImage = _tr.find('.img');
                    // $address = _tr.find('.address'); //仓库
                    $quantity = _tr.find('.quantity'); //数量
                    $price = _tr.find('.price'); //购买单价
                    $disRate = _tr.find('.disRate'); //折扣率
                    $disAmount = _tr.find('.disAmount'); //折扣额
                    $amount = _tr.find('.amount'); //购货金额
                    // $number = _tr.find('.number'); //序列号
                    // $note = _tr.find('.note'); //备注

                    var _this = $(this);
                    var pos = _this.offset();
                    var x = pos.left;
                    var y = pos.top + _this.height();
                    $box.css({
                        left: x,
                        top: y
                    }).html('').hide();
                    $status = true;
                });
                $box.delegate('li', 'click', function (e) {
                    e.stopPropagation();
                    var _this = $(this);
                    //找出存在的sku
                    var isExist = false;
                    $("input[name=specId]").each(function () {
                        if($(this).val() == _this.attr('spec-id')){
                            isExist = true;
                            return;
                        }
                    })

                    if(isExist){
                        alert("添加过了，请勿重复添加")
                        return;
                    }
                    // $id.val(_this.attr('data-id')); //id
                    // var goodsName = _this.text();
                    // var specNumber = _this.attr('spec-no');
                    // var specName = _this.attr('spec-name');
                    // $goodsName.val(specNumber+' '+goodsName+"_"+specName); //商品
                    $goodsName.val(_this.text()); //商品
                    $specNumber.val(_this.attr('spec-no'))
                    $goodsId.val(_this.attr('data-id'))
                    $goodsNumber.val(_this.attr('goods-no'))
                    $specName.val(_this.attr('spec-name'))
                    $colorImage.attr("src",_this.attr('color-image'))
                    $specId.val(_this.attr('spec-id'))
                    $unit.val(_this.attr('data-unit')); //单位
                    // $address.val(_this.attr('data-address')); //仓库
                    // $quantity.val(_this.attr('data-quantity')); //数量
                    $price.val(_this.attr('data-price')); //购买单价
                    $disRate.val(_this.attr('data-rate')); //折扣率
                    $disAmount.val(_this.attr('data-rebate')); //折扣额
                    $amount.val(_this.attr('data-amount')); //购货金额
                    // $number.val(_this.attr('data-number')); //序列号
                    // $note.val(_this.attr('data-note')); //备注

                    $box.hide();
                    $status = false;
                });
                $box.click(function (e) {
                    e.stopPropagation();
                });
                // 商品搜索
                $('#sp-data').delegate('.goods', 'input', function (e) {
                    e.stopPropagation();
                    if ($box.css('display') == 'none') {
                        $box.show();
                    }
                    var key = $(this).val();
                    // ajax..
                    $.ajax({
                        url: "/ajax_goods/goods_spec_search_by_number",
                        type: "POST",
                        dataType: "json",
                        contentType: "application/json",
                        data: JSON.stringify({key: key}),
                        success: function (res) {
                            // alert(res.data.length);
                            $('.sp-result').html("");
                            if (res.code == 0 && res.data.length > 0) {
                                // console.log(res.data);
                                // var data = [];
                                // $(res.data).each(function (i,d) {
                                //     data.push(d.specNumber+" "+d.goodsName+"_"+d.specName);
                                // })
                                render(res.data);
                            }
                            // alert(JSON.stringify(res));
                        }
                    });
                });

                // 商品计算 -start

                var $yhl = $('#yhl'); //优惠率
                var $yhje = $('#yhje'); //优惠金额
                var $yhhje = $('#yhhje'); //优惠后金额
                var $bcfk = $('#bcfk'); //本次付款
                var $bcqk = $('#bcqk'); //本次欠款
                var $totalCount = $("#totalCount");//总数量

                var _yhl = parseFloat($yhl.val()) || 0;
                var _bcfk = parseFloat($bcfk.val()) || 0;

                // 获取总额
                function $getMoney() {
                    var ze = 0;
                    $('.amount').each(function (i, el) {
                        var je = parseFloat($(el).val()) || 0;
                        ze += je;
                    });
                    return ze;
                }

                // 设置总数量
                function $setQuantity() {
                    var quantity = 0;
                    $('.quantity').each(function (i, el) {
                        var je = parseInt($(el).val()) || 0;
                        quantity += je;
                    });
                    $("#totalCount").text(quantity)
                }

                // 设置优惠额 优惠后金额
                function $setMoney() {
                    var ze = $getMoney();
                    var yhje = ze * _yhl / 100;
                    var yhhje = ze - yhje;
                    $yhhje.val(yhhje.toFixed(2));
                    $yhje.val(yhje.toFixed(2));
                }

                // 设置本次欠款
                function $setArrears() {
                    _bcfk = parseFloat($bcfk.val()) || 0;
                    _yhhje = parseFloat($yhhje.val()) || 0;
                    $bcqk.val((_yhhje - _bcfk).toFixed(2));
                }

                // 计算折扣额 购货金额
                function $count(_this) {
                    var _tr = _this.parent('td').parent('tr');
                    var _quantity = _tr.find('.quantity'); // 数量
                    var _price = _tr.find('.price'); //单价
                    var _disRate = _tr.find('.disRate'); //折扣率
                    var _disAmount = _tr.find('.disAmount'); //折扣额
                    var _amount = _tr.find('.amount'); //购货金额

                    // var _sl = parseInt(_quantity.val()) || 0;
                    var _jg = parseFloat(_price.val()) || 0;
                    var _sl = parseInt(_quantity.val()) || 0;
                    var _zkl = parseFloat(_disRate.val()) || 0;

                    // 总额 = 数量 * 单价
                    var ze = _sl * _jg;
                    // 折扣额 = 总额 * 折扣率
                    var zke = ze * _zkl / 100;
                    // 购货金额 = 总额 - 折扣额
                    var ghje = ze - zke;

                    _disAmount.val(zke.toFixed(2));
                    _amount.val(ghje.toFixed(2));
                }

                function $js(_this) {
                    $count(_this);
                    $setMoney();
                    $setArrears();
                    $setQuantity();
                }

                // 数量触发
                $('#sp-data').delegate('.quantity', 'input', function (e) {
                    console.log("数量触发");
                    e.stopPropagation();
                    $js($(this));
                });
                // 单价触发
                $('#sp-data').delegate('.price', 'input', function (e) {
                    console.log("单价触发");
                    e.stopPropagation();
                    $js($(this));
                });
                // 折扣率触发
                $('#sp-data').delegate('.disRate', 'input', function (e) {
                    console.log("折扣率触发");
                    e.stopPropagation();
                    $js($(this));
                });

                // 优惠率触发
                $yhl.on('input', function (e) {
                    _yhl = parseFloat($yhl.val()) || 0;
                    $setMoney();
                    $setArrears();
                });

                // 本次付款触发
                $bcfk.on('input', function (e) {
                    $setArrears();
                });

                // 商品计算 -end

                //首次触发计算
                $js($(".quantity").first());
            }

            init();

            // 新增
            $(document).on('click','.add',function () {
                var newHtml = '<tr>\
					<td> <input type="hidden" name="specNumber" class="specNumber">\n' +
                    '<input type="hidden" name="specId" class="specId">\n' +
                    '<input type="hidden" name="goodsId" class="goodsId">\n' +
                    '<input type="hidden" name="goodsNumber" class="goodsNumber">\n' +
                    '<input type="text" class="goods" placeholder="请输入商品编码" autocomplete="off" style="width: 100%"/></td>\n';

                newHtml+='<td><img style="width: 50px;height: 50px" class="img" /></td>\n' +
                    '<td><input type="text" readonly class="spec" placeholder="规格"/></td>\n' +
                    '<td><input type="text" readonly class="unit" placeholder="单位" /></td>\n';

                // newHtml += '<td><select name="address" class="address"><option disabled selected>请选择</option><option value="深圳库">深圳库</option><option value="本地库">本地库</option></select></td>';
                // newHtml += '<td><select name="address" class="address">';
                // var obj = eval('(' + housesData + ')');
                // $(obj).each(function (i, d) {
                //     newHtml += '<option value="' + d.number + '">' + d.name + '</option>';
                //     // alert(d.name);
                // })
                // newHtml += '</select></td>';

                newHtml += '<td><input type="text" name="quantity" class="quantity" placeholder="请输入" /></td>\
					<td><input type="text" name="price" class="price" placeholder="请输入" /></td>\
					<td><input type="text" name="disRate" class="disRate" placeholder="请输入" /></td>\
					<td><input type="text" name="disAmount" readonly="readonly" class="disAmount" placeholder="折扣金额" /></td>\
					<td><input type="text" name="amount" readonly="readonly" class="amount" placeholder="购货金额" /></td>\
					<td><input type="text" name="note" class="note" placeholder="请输入" /></td>\
					<td><i class="delete">-</i><i class="add">+</i></td>\
				</tr>';


                $('#sp-data').append(newHtml);

            });
            // 删除
            $('#sp-data').delegate('.delete', 'click', function () {
                $(this).parent('td').parent('tr').remove();
            });
            // 保存
            $('#save').click(function () {
                // 获取页面已有的一个form表单
                // var form = document.getElementById("sp-form");
                // 用表单来初始化
                var formData = $('#sp-form').serialize();
                // console.log(formData);
                var supplierId = $("#supplierId").val();
                if (supplierId == '' || supplierId == '0') {
                    alert("请选择供应商");
                    return false;
                }
                var billDate = $("#form_date").val();
                if (billDate == '') {
                    alert("请填写单据日期");
                    return false;
                }
                var userName = $("#userName").val();
                if (userName == '') {
                    alert("请填写制单人");
                    $("#userName").focus();
                    return false;
                }
                // else{
                //     var han = /^[\u4e00-\u9fa5]+$/;
                //     if (!han.test(userName)) {
                //         alert("请填写正确的制单人,必须为中文");
                //         $("#userName").focus();
                //         return false;
                //     };
                // }
                var contractNo = $("input[name='contractNo']").val();
                if (contractNo=="") {
                    alert("请填写合同号");
                    return false;
                }else {
                    var con = /^(?=.*[a-zA-Z]+)(?=.*[0-9]+)[-a-zA-Z0-9]+$/;
                    if (!con.test(contractNo)) {
                        alert("请填写正确的合同号,必须为英文或数字");
                        return false;
                    }
                }
                var supplierId = $("#supplierId").val();
                if (supplierId == '') {
                    alert("请选择供应商");
                    return false;
                }
                
                //检查商品规格
                var returnResult = true;
                var goodsCount = 0;
                //规格颜色
                $("input[name^='specNumber']").each(function (i, el) {
                    if ($(this).val() != "") {
                        //有商品
                        goodsCount++;
                        //检查该行数据
                        // var address = $($("select[name^='address']")[goodsCount - 1]).val();
                        // if (address == undefined || address == '') {
                        //     alert("请选择仓库");
                        //     returnResult = false;
                        //     return false;
                        // }
                        var quantity = $($("input[name^='quantity']")[goodsCount - 1]).val();
                        if (quantity == '' || quantity == '0' || isNaN(quantity)) {
                            alert("请输入数量");
                            returnResult = false;
                            return false;
                        }
                        // var price = $($("input[name^='price']")[goodsCount - 1]).val();
                        // if(price==''||price=='0'||isNaN(price)){
                        //     alert("请输入购货单价");
                        //     returnResult = false;
                        //     return false;
                        // }
                        // var amount = $($("input[name^='amount']")[goodsCount - 1]).val();
                        // if(amount==''||amount=='0'||isNaN(amount)){
                        //     alert("请输入购货金额");
                        //     returnResult = false;
                        //     return false;
                        // }
                    }
                });
                if (returnResult == false) return false;
                if (goodsCount == 0) {
                    alert("请添加商品");
                    return false;
                }

                // alert(JSON.stringify(formData));

                //specNumber
                // return false;
                $('#sp-form').submit();
            });
        });
    </script>
    <!-- end sp-wrapper -->
    <script>
        layui.use('laydate', function () {
            var laydate = layui.laydate;

            //执行一个laydate实例
            laydate.render({
                elem: '#form_date' //指定元素
            });
        });
    </script>
</div>
</body>
<html>
